package com.sinosoft.weixin.controller;

import com.sinosoft.weixin.config.InterfaceAdapterConfig;
import com.sinosoft.weixin.controller.vo.Vo;
import com.sinosoft.weixin.db.entity.OperatorLog;
import com.sinosoft.weixin.db.entity.OperatorLogWithBLOBs;
import com.sinosoft.weixin.db.mapper.OperatorLogMapper;
import com.sinosoft.weixin.service.ServiceChecker;
import com.sinosoft.weixin.shiro.ShiroUtils;
import com.sinosoft.weixin.shiro.UserPrincipal;
import com.sinosoft.weixin.utils.HttpClientUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;

/**
 * Created by huzhengying on 2017/11/21.
 * 接口适配器
 */
@RestController
@RequestMapping("ui/servlet/GCASServlet")
public class InterfaceAdapterController {
    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(InterfaceAdapterController.class);

    @Value("${gcas.addr}")
    private String addr;

    @Autowired
    private OperatorLogMapper operatorLogMapper;
    @Autowired
    private InterfaceAdapterConfig interfaceAdapterConfig;

    @RequestMapping(value = "query",method = RequestMethod.POST)
    public Object query(HttpServletRequest request){
        try{
            String queryCondition = getInputDataString(request);
            ServiceChecker.notNull(queryCondition,"获取前端查询条件失败!");

            String queryResult = HttpClientUtils.sendHttpRequest(
                    queryCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.QUERY));
            if(HttpClientUtils.fail_Result.equals(queryResult)){
                return Vo.fail("查询失败!");
            }

            insertOperatorLog("query",queryCondition,queryResult,request);
            return queryResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }

    }

    @RequestMapping(value = "minute",method = RequestMethod.POST)
    public Object minute(HttpServletRequest request){
        try{
            String queryDetailCondition = getInputDataString(request);
            ServiceChecker.notNull(queryDetailCondition,"获取前端查询条件失败!");

            String queryDetailResult = HttpClientUtils.sendHttpRequest(
                    queryDetailCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.MINUTE));
            if(HttpClientUtils.fail_Result.equals(queryDetailResult)){
                return Vo.fail("明细查询失败!");
            }

            insertOperatorLog("minute",queryDetailCondition,queryDetailResult,request);
            return queryDetailResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }

    }

    @RequestMapping(value = "calprem",method = RequestMethod.POST)
    public Object calprem(HttpServletRequest request){
        try{
            String calPremCondition = getInputDataString(request);
            ServiceChecker.notNull(calPremCondition,"获取前端查询条件失败!");

            String calPremResult = HttpClientUtils.sendHttpRequest(
                    calPremCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.CALPREM));
            if(HttpClientUtils.fail_Result.equals(calPremResult)){
                return Vo.fail("保费计算失败!");
            }

            insertOperatorLog("calprem",calPremCondition,calPremResult,request);
            return calPremResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }

    }

    @RequestMapping(value = "submite",method = RequestMethod.POST)
    public Object submite(HttpServletRequest request){
        try{
            String submitCondition = getInputDataString(request);
            ServiceChecker.notNull(submitCondition,"获取前端查询条件失败!");

            String submitResult = HttpClientUtils.sendHttpRequest(
                    submitCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.SUBMITE));
            if(HttpClientUtils.fail_Result.equals(submitResult)){
                return Vo.fail("提交信息失败!");
            }

            insertOperatorLog("submite",submitCondition,submitResult,request);
            return submitResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }

    }


    @RequestMapping(value = "claimRate",method = RequestMethod.POST)
    public Object claimRate(HttpServletRequest request){

        try{
            String submitCondition = getInputDataString(request);
            ServiceChecker.notNull(submitCondition,"获取前端查询条件失败!");

            String submitResult = HttpClientUtils.sendHttpRequest(
                    submitCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.CLAIMRATE));
            if(HttpClientUtils.fail_Result.equals(submitResult)){
                return Vo.fail("提交信息失败!");
            }

            insertOperatorLog("claimRate",submitCondition,submitResult,request);
            return submitResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }
    }

    @RequestMapping(value = "deleteRisk",method = RequestMethod.POST)
    public Object deleteRisk(HttpServletRequest request){

        try{
            String submitCondition = getInputDataString(request);
            ServiceChecker.notNull(submitCondition,"获取前端查询条件失败!");

            String submitResult = HttpClientUtils.sendHttpRequest(
                    submitCondition,
                    interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.DELETERISK));
            if(HttpClientUtils.fail_Result.equals(submitResult)){
                return Vo.fail("提交信息失败!");
            }

            insertOperatorLog("deleteRisk",submitCondition,submitResult,request);
            return submitResult;
        }catch (Exception ex){
            return Vo.fail(ex.getMessage());
        }
    }

    /**
     * 将前端传入的输入流转为字符串
     * @param request
     * @return
     */
    private String getInputDataString(HttpServletRequest request){

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String readLine = "";
            while ((readLine = br.readLine()) != null) {
                buffer.append(readLine + "\n");
            }
            String convertInputData = buffer.toString();
            logger.info("inputdata:"+convertInputData);
            return convertInputData;
        } catch (Exception ex) {
            logger.error(ex);
        } finally {
            IOUtils.closeQuietly(br);
        }
        return null;
    }

    /**
     * 插入操作轨迹
     * @param funcflag 交易类型
     * @param inputDate 输入数据
     * @param outputDate 返回数据
     */
    private void insertOperatorLog(String funcflag,String inputDate,String outputDate,HttpServletRequest request){
        try{
            UserPrincipal userPrincipal = ShiroUtils.getCurrentUserPrincipal();
            OperatorLogWithBLOBs operatorLog = new OperatorLogWithBLOBs();
            operatorLog.setWorkNumber(userPrincipal.getWorkNumber());
            operatorLog.setFuncFlag(funcflag);
            operatorLog.setOperatorDate(new Date());
            operatorLog.setInputData(inputDate);
            operatorLog.setOutputData(outputDate);
            operatorLog.setRemark(getRemoteRequestIp(request));

            operatorLogMapper.insert(operatorLog);
        }catch (Exception ex){
            logger.error("插入日志失败!",ex);
        }
    }

    private static String getRemoteRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }


}
